// 引入请求接口方法
import { login, logout, getInfo } from '@/api/user'
// 导入控制token的工具方法
import { getToken, setToken, removeToken } from '@/utils/auth'
// 导入路由文件resetRouter重置路由对象方法
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(), // token字符串(默认值会通过getToken()这个方法从浏览器本地cookie中获取)
    name: '', // 用户名
    avatar: '' // 用户头像
  }
}

// state对象来自于上边方法的一个返回值
const state = getDefaultState()

const mutations = {
  // 重置state对象
  RESET_STATE: (state) => {
    // Object.assign,把参数2中的所有属性键值对都合并到参数1上
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      // login() 在调用接口方法,发请求
      login({ username: username.trim(), password: password }).then(response => {
        // 拿到response响应数据
        const { data } = response
        // 将token值交到mutations中,更改state中的token的值
        commit('SET_TOKEN', data.token)
        // 将最新获取的token值存储到cookie中
        setToken(data.token)
        // 告诉逻辑页面login.vue那边,登陆成功promise兑现触发那边的then
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { name, avatar } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 用户退出登录
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 清除token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

